package cn.jinjimi.app.main.widget.ToolBar;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.datasource.DataSubscriber;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.webview.DynamicMoreWindow;
import cn.jinjimi.app.main.widget.ToggleButton;

import java.util.List;

/**
 * Created by Roy
 * Date: 16/7/25
 */
public class WebToolbar extends android.support.v7.widget.Toolbar {

    ImageView mBackIv, mCloseIv;
    TextView mBackTx, mCloseTx;

    TextView mTitleTx;

    ViewGroup mExpActions;
    DynamicMoreWindow mMenuWindow;


    public WebToolbar(Context context) {
        this(context, null, 0);
    }

    public WebToolbar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WebToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        inflate(context, R.layout.base_toolbar_layout, this);

        initView();
    }

    private void initView() {
        mBackIv = (ImageView) findViewById(R.id.toolbar_back_btn);
        mBackTx = (TextView) findViewById(R.id.toolbar_back_tx);

        mCloseIv = (ImageView) findViewById(R.id.toolbar_close_btn);
        mCloseTx = (TextView) findViewById(R.id.toolbar_close_tx);

        mTitleTx = (TextView) findViewById(R.id.toolbar_title);

        mExpActions = (ViewGroup) findViewById(R.id.toolbar_exp_actions);

    }

    private View newActionSwitcher() {
        return inflate(getContext(), R.layout.widget_switcher, null);
    }

    private View newActionSwitcher(View v, ToolbarActionSwitcher action) {

        if (v == null) {
            return null;
        }

        ToggleButton button = (ToggleButton) v.findViewById(R.id.tgb_show);

        if (button == null) {
            return v;
        }

        return v;
    }

    private View newActionButton() {
        return inflate(getContext(), R.layout.widget_action, null);
    }

    private View newActionButton(View v, ToolbarAction action) {

        if (v == null) {
            return null;
        }

        TextView label = (TextView) v.findViewById(R.id.toolbar_action_tx);
        ImageView image = (ImageView) v.findViewById(R.id.toolbar_action_btn);

        if (label == null || image == null) {
            return v;
        }

        label.setVisibility(View.VISIBLE);
        image.setVisibility(View.GONE);

        if (action != null) {
            label.setText(action.label);
            if (action.icon != null) {
                label.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
                int drawableSize = getResources().getDimensionPixelSize(R.dimen.dp_12);

                action.icon.setBounds(0, 0, drawableSize, drawableSize);
                label.setCompoundDrawablesWithIntrinsicBounds(null, null, action.icon, null);
                label.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
                label.setSelected(false);
            }
        }

        return v;
    }


    private View newActionImage(View v, ToolbarActionImage action) {

        if (v == null) {
            return null;
        }

        TextView label = (TextView) v.findViewById(R.id.toolbar_action_tx);
        ImageView image = (ImageView) v.findViewById(R.id.toolbar_action_btn);

        if (label == null || image == null) {
            return v;
        }

        label.setVisibility(View.GONE);
        image.setVisibility(View.VISIBLE);

        if (action != null) {

            if (!TextUtils.isEmpty(action.imgUrl)) {
                loadImageFromUrl(image, action.imgUrl);
            } else if (action.icon != null) {
                image.setImageDrawable(action.icon);
            }
        }

        return v;
    }

    private View newActionMore(View v, ToolbarActionMore action) {

        if (v == null) {
            return null;
        }

        ImageView image = (ImageView) v.findViewById(R.id.toolbar_action_btn);
        View label = v.findViewById(R.id.toolbar_action_tx);

        if (label == null || image == null) {
            return v;
        }

        image.setImageResource(R.drawable.nav_icon_more);
        image.setVisibility(View.VISIBLE);
        label.setVisibility(View.GONE);

        return v;
    }

    private View adaptActionButtonView(ToolbarAction action) {

        View v;

        switch (action.type) {
            case ToolbarAction.TYPE_SWITCHER:
                v = newActionSwitcher(newActionSwitcher(), (ToolbarActionSwitcher) action);
                break;

            case ToolbarAction.TYPE_MORE:
                v = newActionMore(newActionButton(), (ToolbarActionMore) action);
                break;

            case ToolbarAction.TYPE_IMAGE:
                v = newActionImage(newActionButton(), (ToolbarActionImage) action);
                break;

            case ToolbarAction.TYPE_TEXT:
            default:
                v = newActionButton(newActionButton(), action);
                break;

        }

        return v;
    }


    /**
     * The toolbar action Data Structure
     */
    public static class ToolbarAction {
        /**
         * Switcher
         */
        public static final int TYPE_SWITCHER = 2;

        /**
         * image button
         */
        public static final int TYPE_IMAGE = 1;

        /**
         * text with(or not) icon
         */
        public static final int TYPE_TEXT = 0;

        /**
         * more actions
         */
        public static final int TYPE_MORE = 3;

        /**
         * 类型
         */
        public final int type;

        /**
         * 标签
         */
        public String label;

        /**
         * 图标
         */
        public Drawable icon;

        /**
         * 链接
         */
        public String link;

        public ToolbarAction(String label, int type) {
            this.label = label;
            this.type = type;
        }

        public ToolbarAction(String label) {
            this.label = label;
            this.type = TYPE_TEXT;
        }

        @Override
        public boolean equals(Object o) {

            if (o != null && o instanceof ToolbarAction) {

                try {
                    ToolbarAction action = (ToolbarAction) o;
                    if (action.label.equals(label)
                            && action.type == type) {
                        return true;
                    }
                } catch (Exception e) {
                    //e.printStackTrace();
                }
            }

            return false;
        }

    }

    public static class ToolbarActionImage extends ToolbarAction {
        public String imgUrl;

        public ToolbarActionImage(String label) {
            super(label, TYPE_IMAGE);
        }
    }

    public static class ToolbarActionSwitcher extends ToolbarAction {
        public ToolbarActionSwitcher(String label) {
            super(label, TYPE_SWITCHER);
        }
    }

    public static class ToolbarActionMore extends ToolbarAction {
        public ToolbarActionMore(String label) {
            super(label, TYPE_MORE);
        }
    }

    public View getActionButton(int position) {
        return mExpActions.getChildAt(position);
    }

    public View getActionButtonByTag(ToolbarAction tag) {
        return mExpActions.findViewWithTag(tag);
    }

    public View putActionButton(ToolbarAction action, OnClickListener listener) {

        View v = adaptActionButtonView(action);

        v.setTag(action);
        v.setOnClickListener(listener);

        mExpActions.addView(v);

        return v;
    }

    public void putActionButtonArray(List<ToolbarAction> actions, OnClickListener listener) {
        if (actions != null) {
            removeAllActionButtons();
            if (actions.size() <= 2) {
                for (ToolbarAction action : actions) {
                    putActionButton(action, listener);
                }
            } else {
                createDropdownMenu(actions, listener);
            }
        }
    }

    public void removeActionButton(ToolbarAction tag) {
        View v = mExpActions.findViewWithTag(tag);
        if (v != null) {
            mExpActions.removeView(v);
        }
    }

    public void removeAllActionButtons() {
        mExpActions.removeAllViews();
    }

    /**
     *  创建下拉菜单栏
     */
    private void createDropdownMenu(List<ToolbarAction> actions, OnClickListener listener) {
        if (mMenuWindow == null) {
            mMenuWindow = new DynamicMoreWindow(getContext());
        }
        mMenuWindow.setData(actions, listener);

        ToolbarActionMore more = new ToolbarActionMore("more");

        final View v = putActionButton(more, new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMenuWindow != null) {
                    mMenuWindow.showAsDropDown(v);
                }
            }
        });

        v.post(new Runnable() {
            @Override
            public void run() {
                mMenuWindow.showAsDropDown(v);
                mMenuWindow.update();
            }
        });

    }

    private void loadImageFromUrl(final ImageView imageBtn, final String imgUrl) {
        if (StringUtils.isNotEmpty(imgUrl)) {
            ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(imgUrl)).build();
            ImagePipeline imagePipeline = Fresco.getImagePipeline();

            DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, this);

            DataSubscriber dataSubscriber = new BaseDataSubscriber<CloseableReference<CloseableImage>>() {

                @Override
                protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
                    if (!dataSource.isFinished()) {
                        LogUtil.d("Not yet finished - this is just another progressive scan.");
                    }

                    CloseableReference<CloseableImage> imageReference = dataSource.getResult();
                    if (imageReference != null) {
                        try {
                            CloseableBitmap image = (CloseableBitmap) imageReference.get();
                            final Bitmap loadedImage = image.getUnderlyingBitmap();
                            if (imageBtn == null || loadedImage == null)
                                return;
                            TaskExecutor.runTaskOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    imageBtn.setVisibility(View.VISIBLE);
                                    imageBtn.setImageBitmap(loadedImage);
                                }
                            });

                        } finally {
                            dataSource.close();
                            CloseableReference.closeSafely(imageReference);
                        }
                    }
                }

                @Override
                protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
                    TaskExecutor.runTaskOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (imageBtn != null) {
                                imageBtn.setVisibility(View.VISIBLE);
                                imageBtn.setImageResource(R.drawable.nav_icon_common);
                            }
                        }
                    });

                }
            };

            dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());
        }
    }


    /**
     * 设置标题栏
     *
     * @param title
     */
    public final void setTitle(String title) {
        mTitleTx.setText(title);
    }

    /**
     * 设置标题栏
     *
     * @param strRes
     */
    public final void setTitle(int strRes) {
        mTitleTx.setText(strRes);
    }

    /**
     * 普通的标题栏 只有标题和返回按钮
     *
     * @param title
     */
    public final void baseTitle(CharSequence title) {
        mTitleTx.setText(title);
        mBackIv.setVisibility(VISIBLE);
    }

    /**
     * 显示二级返回的关闭按钮
     *
     * @param show
     * @param text
     */
    public final void setmCloseIv(boolean show, String text) {
        if (show) {
            mCloseIv.setVisibility(VISIBLE);
            mCloseTx.setVisibility(GONE);
        } else {
            mCloseIv.setVisibility(GONE);
            mCloseTx.setVisibility(VISIBLE);
            mCloseTx.setText(text);
        }

    }

    @Override
    public void setOnClickListener(OnClickListener l) {
        mBackIv.setOnClickListener(l);
        mBackTx.setOnClickListener(l);
        mCloseTx.setOnClickListener(l);
        mCloseIv.setOnClickListener(l);

        mExpActions.setOnClickListener(l);
        super.setOnClickListener(l);
    }

    public ImageView getmBackIv() {
        return mBackIv;
    }

    public ImageView getmCloseIv() {
        return mCloseIv;
    }

}
